package rysi.ips2014.control;

import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import rysi.ips2014.articulosweb.modelo.Articulo;
import rysi.ips2014.articulosweb.modelo.TipoArticulo;
import rysi.ips2014.articulosweb.oad.ArticuloOad;
import rysi.ips2014.articulosweb.oad.TipoArticuloOad;

/**
 *
 * @author PCEL
 */

@Controller
public class ControladorArticulos {

    @Autowired
    ArticuloOad articuloOad;

    @Autowired
    TipoArticuloOad tipoArticuloOad;
    
    @RequestMapping("listarArticulos")
    public ModelAndView listarArticulos() {
        ModelAndView mav = new ModelAndView("articulos");
        mav.addObject("articulos", articuloOad.findAll());
        return mav;
    }
    
    @RequestMapping("nuevoArticulo")
    public ModelAndView nuevoArticulo() {
        ModelAndView mav = new ModelAndView("nuevoArticulo");
        Articulo art = new Articulo();
        art.setTipo(new TipoArticulo());
        mav.addObject("articulo", art);
        mav.addObject("fechaActualEnServidor", new Date());
        mav.addObject("tiposArticulos", tipoArticuloOad.findAll());
        return mav;
    }
    
    @RequestMapping(value = "agregarArticulo", method = RequestMethod.POST)
    public String agregarArticulo(@ModelAttribute Articulo articulo, BindingResult result, Model model) {
        if (result.hasErrors()) {
            model.addAttribute("articulo", articulo);
            return "nuevoArticulo";
        }
        if (articulo.getTipo().getIdTipo() > 0) {
            TipoArticulo tipo = tipoArticuloOad.findOne(articulo.getTipo().getIdTipo());
            articulo.setTipo(tipo);
        }
        articuloOad.save(articulo);
        return "redirect:/listarArticulos";                              
    }
}
